package Core
{
	import flash.display.*;
	import flash.events.*;
 
	/**
	 * отслеживание нажатых клавиш
	 * @author silin
	 */
	public class KeysUtil
	{
		private static var _keys:Array = [];
		private static var _stage:Stage;
		private static var _enabled:Boolean = true;
		
		public static function Register(stage:Stage):void
		{
			_stage = stage;
			_stage.addEventListener(KeyboardEvent.KEY_DOWN, KeyDownHandler);
			_stage.addEventListener(KeyboardEvent.KEY_UP, KeyUpHandler);
		}
 
		private static function KeyUpHandler(evnt:KeyboardEvent):void 
		{
			for (var i:int = 0; i < _keys.length; i++) 
			{
				if (_keys[i] == evnt.keyCode) _keys.splice(i, 1);
			}
		}
 
		private static function KeyDownHandler(evnt:KeyboardEvent):void 
		{
			var key:int = evnt.keyCode;
 
			for (var i:int = 0; i < _keys.length; i++) 
			{
				if (_keys[i] == key) return;
			}
			_keys.push(key);
		}
 
		public static function IsKeyDown(key:int):Boolean
		{
			for (var i:int = 0; i < _keys.length; i++) 
			{
				if (_keys[i] == key) 
				{
					return true;
				}
			}
			return false;
		}
 
		public static function get lastPressed():int 
		{ 
			return _keys.length ? _keys[_keys.length - 1] : 0;
		}
 
		static public function get enabled():Boolean { return _enabled; }
 
		static public function set enabled(value:Boolean):void 
		{
			if (_enabled == value) return;
			_enabled = value;
			_keys = [];
			if (_enabled)
			{
				_stage.addEventListener(KeyboardEvent.KEY_DOWN, KeyDownHandler);
				_stage.addEventListener(KeyboardEvent.KEY_UP, KeyUpHandler);
			}else
			{
				_stage.removeEventListener(KeyboardEvent.KEY_DOWN, KeyDownHandler);
				_stage.removeEventListener(KeyboardEvent.KEY_UP, KeyUpHandler);
			}
		}
 
	}
 
}